package io;

import java.io.*;
import java.util.Scanner;

public class IODemo15 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径:");
        String rootPath = scanner.nextLine();
        System.out.println("请输入要搜索的词");
        String word = scanner.nextLine();
        //路径合法性判断
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("输入的路径有误!");
            return;
        }

        scanDir(rootFile,word);
    }
    private static void scanDir(File rootFile, String word) {
        System.out.println("当前遍历到:" + rootFile.getAbsolutePath());

        File[] files = rootFile.listFiles();
        if(files == null) {
            return;
        }
        for(File f : files) {
            if(f.isDirectory()) {
                scanDir(f,word);
            }else if(f.isFile()) {
                scanInFile(f,word);
            }else {
                //暂时不用
            }
        }
    }
    private static void scanInFile(File f,String word) {
        try(InputStream inputStream = new FileInputStream(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while(true) {
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1) {
                    break;
                }
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }
            if(stringBuilder.indexOf(word) != -1) {
                System.out.println("找到了! " + word + " 存在于:" + f.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
